package com.bing.util;

import com.bing.bean.baidu.Json_User;
import com.bing.bean.baidu.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2015/3/8 0008.
 */
public class SoUtil {

    private static final Logger logger = LoggerFactory.getLogger(SoUtil.class);
    private static Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }


    public static String decodeUrl(String url) {
        try {
            return URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return url;
        }
    }

    public static <T> T json2T(String url, Class<T> classz, Map<String, String> cookies) {
        T t = null;
        String result = null;
        logger.info("提取:{},{}", classz, url);
        try {
            result = Jsoup.connect(url).ignoreContentType(true).timeout(Constant.TIMEOUT).userAgent(Constant.USER_AGENT).cookies(cookies).execute().body();
            result = unicodeToString(result);
            logger.info("获取数据:{}", result);
            t = gson.fromJson(result, classz);
        } catch (Exception e) {
            logger.error("失败", e);
        }
        return t;
    }

    public static User get(int uk, Map<String, String> cookies) {
        String url = String.format(Constant.userInfo, uk, System.currentTimeMillis());
        logger.info("获取用户信息:{}", uk);
        Json_User json_user = json2T(url, Json_User.class, cookies);
        if (json_user != null) {
            logger.info("", json_user.getUser_info());
            return json_user.getUser_info();
        }
        logger.info("用户空:{}", uk);
        return null;
    }

}
